package net.hn.hnms.biz.mine.group.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.hn.hnms.biz.mine.domain.MineCodeMapPo;
import net.hn.hnms.biz.mine.domain.OtherApiURL;
import net.hn.hnms.biz.mine.domain.dto.MiningSystemRunTimeDayDto;
import net.hn.hnms.biz.mine.domain.dto.MiningSystemRunTimeMinuteDetailDto;
import net.hn.hnms.biz.mine.domain.vo.EffectiveProductionTimeMonthlyStatisticsVo;
import net.hn.hnms.biz.mine.domain.vo.EffectiveProductionTimeVo;
import net.hn.hnms.biz.mine.mapper.MineCodeMapMapper;
import net.hn.hnms.biz.mine.service.OtherSystemApiService;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GroupServiceImpl implements GroupService {

    /**
     * 编码映射表
     */
    @Resource
    private MineCodeMapMapper mineCodeMapMapper;
    @Resource
    private OtherSystemApiService otherSystemApiService;
    /**
     * 大屏-矿井有效生产时长
     * @return
     */
    @Override
    public List<EffectiveProductionTimeVo> getEffectiveProductionTimeList() {
        //查询当前映射表的所有数据
        List<MineCodeMapPo> mineCodeMapPos = mineCodeMapMapper.selectList(
                new LambdaQueryWrapper<MineCodeMapPo>()
//                        .eq(StringUtils.isNotBlank(mineCode), MineCodeMapPo::getMineCode, mineCode)
                        //升序
                        .orderByAsc(MineCodeMapPo::getSort));
        if (mineCodeMapPos.isEmpty()) {
            throw new HuaNengException(Constants.FAIL, "无法查询到煤矿列表，请检查mine_code_map表");
        }
        // 获取今日的开始时间
        Calendar startCal = Calendar.getInstance();
        startCal.set(Calendar.HOUR_OF_DAY, 0);
        startCal.set(Calendar.MINUTE, 0);
        startCal.set(Calendar.SECOND, 0);
        Date startDate = startCal.getTime();

        // 获取今日的结束时间
        Calendar endCal = Calendar.getInstance();
        endCal.set(Calendar.HOUR_OF_DAY, 23);
        endCal.set(Calendar.MINUTE, 59);
        endCal.set(Calendar.SECOND, 59);
        Date endDate = endCal.getTime();


        //遍历映射表
        List<EffectiveProductionTimeVo> collect = mineCodeMapPos.stream().map(t -> {
            EffectiveProductionTimeVo effectiveProductionTimeVo = new EffectiveProductionTimeVo();
            if ("150781013670".equals(t.getMineCode())) {
                //灵东
                //获取ip
                String ip = OtherApiURL.LINGDONG_IP;
                //获取appSecret
                String appSecret = OtherApiURL.LINGDONG_APP_SECRET;
                //获取时间戳
                String timeStamp = String.valueOf(System.currentTimeMillis());
                extracted(startDate, endDate, effectiveProductionTimeVo, ip, appSecret, timeStamp);

            } else if ("150781013603".equals(t.getMineCode())) {
                //灵泉
                //获取ip
                String ip = OtherApiURL.LINGQUAN_IP;
                //获取appSecret
                String appSecret = OtherApiURL.LINGQUAN_APP_SECRET;
                //获取时间戳
                String timeStamp = String.valueOf(System.currentTimeMillis());
                extracted(startDate, endDate, effectiveProductionTimeVo, ip, appSecret, timeStamp);
            } else if ("150781013194".equals(t.getMineCode())) {
                //铁北
                //获取ip
                String ip = OtherApiURL.TIEBEI_IP;
                //获取appSecret
                String appSecret = OtherApiURL.TIEBEI_APP_SECRET;
                //获取时间戳
                String timeStamp = String.valueOf(System.currentTimeMillis());
                extracted(startDate, endDate, effectiveProductionTimeVo, ip, appSecret, timeStamp);
            } else {
                ////如果都不是则填充默认值
                effectiveProductionTimeVo.setRunTimeMinute("---");
                effectiveProductionTimeVo.setRunTimeHourMinute("---");
                effectiveProductionTimeVo.setMinuteDetailList(new ArrayList<>());
            }
            effectiveProductionTimeVo.setMineName(t.getMineName());
            effectiveProductionTimeVo.setMineCode(t.getMineCode());

            return effectiveProductionTimeVo;
        }).collect(Collectors.toList());
        return collect;
    }
    private void extracted(Date startDate, Date endDate, EffectiveProductionTimeVo effectiveProductionTimeVo, String ip, String appSecret, String timeStamp) {
        //获取认证
        String signature = otherSystemApiService.getSignature(OtherApiURL.APP_KEY, appSecret, timeStamp);
        //获取 采煤每日运行总时长
        List<MiningSystemRunTimeDayDto> miningSystemRunTimeDay = otherSystemApiService.getMiningSystemRunTimeDay(ip, signature, timeStamp, startDate, endDate);
        if (!miningSystemRunTimeDay.isEmpty()) {
            //获取扎煤采煤时长
            Integer duration = miningSystemRunTimeDay.get(0).getGzscH();
            effectiveProductionTimeVo.setRunTimeMinute(String.valueOf(duration) + "小时");

            int fullHours = (int) duration; // 获取整数部分作为小时
            int minutes = (int) ((duration - fullHours) * 60); // 将小数部分表示为分钟

            String timeString = fullHours + "h " + minutes + "min"; // 格式化时间字符串
            effectiveProductionTimeVo.setRunTimeHourMinute(timeString);
        } else {
            effectiveProductionTimeVo.setRunTimeMinute("---");
            effectiveProductionTimeVo.setRunTimeHourMinute("---");
        }
        //获取分钟详细列表
        List<MiningSystemRunTimeMinuteDetailDto> miningSystemRunTimeMinuteDetail = otherSystemApiService.getMiningSystemRunTimeMinuteDetail(ip, signature, timeStamp, startDate, endDate);
        if (!miningSystemRunTimeMinuteDetail.isEmpty()) {
            //获取详情列表
            effectiveProductionTimeVo.setMinuteDetailList(miningSystemRunTimeMinuteDetail);
        } else {
            effectiveProductionTimeVo.setMinuteDetailList(new ArrayList<>());
        }
    }
    /**
     * 大屏-矿井有效生产时长月统计
     * @param mineCode
     * @return
     */
    @Override
    public EffectiveProductionTimeMonthlyStatisticsVo getEffectiveProductionTimeMonthlyStatistics(String mineCode) {
        if (StringUtils.isBlank(mineCode)) {
            throw new HuaNengException(Constants.FAIL, "煤矿编码不可以为空：" + mineCode);
        }
        // 获取这个月的第一天的日期时间
        LocalDateTime startOfMonth = LocalDateTime.of(LocalDate.now().withDayOfMonth(1), LocalTime.MIN);
        // 转换为 Date 类型
        Date startDate = Date.from(startOfMonth.atZone(Calendar.getInstance().getTimeZone().toZoneId()).toInstant());
        // 获取这个月的最后一天的日期时间
        LocalDateTime endOfMonth = LocalDateTime.of(LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()), LocalTime.MAX);
        //转化为Date类型
        Date endDate = Date.from(endOfMonth.atZone(Calendar.getInstance().getTimeZone().toZoneId()).toInstant());

        //获取运行时长集合
        List<MiningSystemRunTimeDayDto> runTimeDayDtoList=null;

        if ("150781013670".equals(mineCode)) {
            //灵东
            //获取ip
            String ip = OtherApiURL.LINGDONG_IP;
            //获取appSecret
            String appSecret = OtherApiURL.LINGDONG_APP_SECRET;
            //获取时间戳
            String timeStamp = String.valueOf(System.currentTimeMillis());
            //获取认证
            String signature = otherSystemApiService.getSignature(OtherApiURL.APP_KEY, appSecret, timeStamp);
            //获取每日运行时长
            runTimeDayDtoList = otherSystemApiService.getMiningSystemRunTimeDay(ip, signature, timeStamp, startDate, endDate);

        } else if ("150781013603".equals(mineCode)) {
            //灵泉
            //获取ip
            String ip = OtherApiURL.LINGQUAN_IP;
            //获取appSecret
            String appSecret = OtherApiURL.LINGQUAN_APP_SECRET;
            //获取时间戳
            String timeStamp = String.valueOf(System.currentTimeMillis());
            //获取认证
            String signature = otherSystemApiService.getSignature(OtherApiURL.APP_KEY, appSecret, timeStamp);
            //获取每日运行时长
            runTimeDayDtoList = otherSystemApiService.getMiningSystemRunTimeDay(ip, signature, timeStamp, startDate, endDate);
        } else if ("150781013194".equals(mineCode)) {
            //铁北
            //获取ip
            String ip = OtherApiURL.TIEBEI_IP;
            //获取appSecret
            String appSecret = OtherApiURL.TIEBEI_APP_SECRET;
            //获取时间戳
            String timeStamp = String.valueOf(System.currentTimeMillis());
            //获取认证
            String signature = otherSystemApiService.getSignature(OtherApiURL.APP_KEY, appSecret, timeStamp);
            //获取每日运行时长
            runTimeDayDtoList = otherSystemApiService.getMiningSystemRunTimeDay(ip, signature, timeStamp, startDate, endDate);
        } else {
            runTimeDayDtoList = new ArrayList<>();
        }
        //返回数据实体类
        EffectiveProductionTimeMonthlyStatisticsVo effectiveProductionTimeMonthlyStatisticsVo = new EffectiveProductionTimeMonthlyStatisticsVo();
        List<Integer> runTimeList = new ArrayList<>();
         List<Date> dateTimeList = new ArrayList<>();
        if (!runTimeDayDtoList.isEmpty()) {
            // 将 List 转换为 Map
            Map<Integer, MiningSystemRunTimeDayDto> runTimeDayDtoMap = runTimeDayDtoList.stream()
                    .collect(Collectors.toMap(MiningSystemRunTimeDayDto::getTaskId, dto -> dto));

            //本月初第一天
            // 从开始时间循环增加一天，直到结束时间
            LocalDateTime currentDateTime = startOfMonth;
            while (currentDateTime.isBefore(endOfMonth) || currentDateTime.isEqual(endOfMonth)) {
                //转化为Date日期
                Date dateTime = Date.from(currentDateTime.atZone(Calendar.getInstance().getTimeZone().toZoneId()).toInstant());
                //将date 转为yyyyMMdd形式
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                String dateString = formatter.format(dateTime);
                //判断时间是否相同
                Integer gzscH = 0;
                if (dateString.equals(String.valueOf(runTimeDayDtoMap.get(Integer.valueOf(dateString)).getTaskId()))) {
                    MiningSystemRunTimeDayDto miningSystemRunTimeDayDto = runTimeDayDtoMap.get(Integer.valueOf(dateString));
                    gzscH = miningSystemRunTimeDayDto.getGzscH();
                }
                //存放运行时长
                runTimeList.add(gzscH);
                //存放时间
                dateTimeList.add(dateTime);
                currentDateTime = currentDateTime.plusDays(1);
            }

        } else {
            return effectiveProductionTimeMonthlyStatisticsVo;
        }
        effectiveProductionTimeMonthlyStatisticsVo.setRunTimeList(runTimeList);
        effectiveProductionTimeMonthlyStatisticsVo.setDateTimeList(dateTimeList);
        effectiveProductionTimeMonthlyStatisticsVo.setMineCode(mineCode);
        return effectiveProductionTimeMonthlyStatisticsVo;
    }


}
